// AI Therapist Main JavaScript File

// Global variables
let currentEmotion = 'positive';
let emotionChart;
let chatHistory = [];
let isTyping = false;

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    initializeAnimations();
    initializeEmotionChart();
    initializeChatInterface();
    initializeBackgroundEffect();
    loadChatHistory();
});

// Initialize page animations
function initializeAnimations() {
    // Animate hero elements
    anime.timeline({
        easing: 'easeOutExpo',
        duration: 1000
    })
    .add({
        targets: '#main-title',
        opacity: [0, 1],
        translateY: [50, 0],
        delay: 300
    })
    .add({
        targets: '#subtitle',
        opacity: [0, 1],
        translateY: [30, 0],
        delay: 200
    }, '-=800')
    .add({
        targets: '#start-btn',
        opacity: [0, 1],
        translateY: [20, 0],
        scale: [0.9, 1],
        delay: 100
    }, '-=600');

    // Animate feature cards
    anime({
        targets: '.feature-card',
        opacity: [0, 1],
        translateY: [50, 0],
        delay: anime.stagger(200, {start: 1000}),
        duration: 800,
        easing: 'easeOutExpo'
    });
}

// Initialize emotion chart
function initializeEmotionChart() {
    const chartDom = document.getElementById('emotion-chart');
    emotionChart = echarts.init(chartDom);
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%',
            top: '10%'
        },
        xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            axisLine: {
                lineStyle: {
                    color: '#E5E7EB'
                }
            },
            axisLabel: {
                color: '#6B7280',
                fontSize: 10
            }
        },
        yAxis: {
            type: 'value',
            min: -1,
            max: 1,
            axisLine: {
                lineStyle: {
                    color: '#E5E7EB'
                }
            },
            axisLabel: {
                color: '#6B7280',
                fontSize: 10,
                formatter: function(value) {
                    if (value === 1) return '积极';
                    if (value === 0) return '中性';
                    if (value === -1) return '消极';
                    return '';
                }
            },
            splitLine: {
                lineStyle: {
                    color: '#F3F4F6'
                }
            }
        },
        series: [{
            name: '情绪指数',
            type: 'line',
            data: [0.2, 0.4, 0.1, 0.6, 0.3, 0.7, 0.5],
            smooth: true,
            lineStyle: {
                color: '#4A90A4',
                width: 3
            },
            itemStyle: {
                color: '#4A90A4',
                borderWidth: 2,
                borderColor: '#fff'
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(74, 144, 164, 0.3)'
                    }, {
                        offset: 1, color: 'rgba(74, 144, 164, 0.05)'
                    }]
                }
            }
        }]
    };
    
    emotionChart.setOption(option);
    
    // Make chart responsive
    window.addEventListener('resize', function() {
        emotionChart.resize();
    });
}

// Initialize chat interface
function initializeChatInterface() {
    const chatInput = document.getElementById('chat-input');
    
    chatInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    
    // Add typing indicator event
    chatInput.addEventListener('input', function() {
        if (!isTyping) {
            simulateTypingIndicator();
        }
    });
}

// Initialize background effect with p5.js
function initializeBackgroundEffect() {
    new p5(function(p) {
        let particles = [];
        let numParticles = 50;
        
        p.setup = function() {
            let canvas = p.createCanvas(p.windowWidth, p.windowHeight);
            canvas.parent('p5-background');
            
            // Create particles
            for (let i = 0; i < numParticles; i++) {
                particles.push({
                    x: p.random(p.width),
                    y: p.random(p.height),
                    vx: p.random(-0.5, 0.5),
                    vy: p.random(-0.5, 0.5),
                    size: p.random(2, 6),
                    alpha: p.random(0.1, 0.3)
                });
            }
        };
        
        p.draw = function() {
            p.clear();
            
            // Update and draw particles
            for (let particle of particles) {
                particle.x += particle.vx;
                particle.y += particle.vy;
                
                // Wrap around edges
                if (particle.x < 0) particle.x = p.width;
                if (particle.x > p.width) particle.x = 0;
                if (particle.y < 0) particle.y = p.height;
                if (particle.y > p.height) particle.y = 0;
                
                // Draw particle
                p.fill(74, 144, 164, particle.alpha * 255);
                p.noStroke();
                p.ellipse(particle.x, particle.y, particle.size);
            }
            
            // Draw connections
            for (let i = 0; i < particles.length; i++) {
                for (let j = i + 1; j < particles.length; j++) {
                    let dist = p.dist(particles[i].x, particles[i].y, particles[j].x, particles[j].y);
                    if (dist < 100) {
                        let alpha = p.map(dist, 0, 100, 0.1, 0);
                        p.stroke(74, 144, 164, alpha * 255);
                        p.strokeWeight(1);
                        p.line(particles[i].x, particles[i].y, particles[j].x, particles[j].y);
                    }
                }
            }
        };
        
        p.windowResized = function() {
            p.resizeCanvas(p.windowWidth, p.windowHeight);
        };
    });
}

// Chat functionality
function startChat() {
    const chatInput = document.getElementById('chat-input');
    chatInput.focus();
    
    // Smooth scroll to chat area
    document.querySelector('.chat-container').scrollIntoView({
        behavior: 'smooth',
        block: 'center'
    });
}

function sendMessage() {
    const chatInput = document.getElementById('chat-input');
    const message = chatInput.value.trim();
    
    if (!message) return;
    
    // Add user message to chat
    addMessageToChat(message, 'user');
    
    // Clear input
    chatInput.value = '';
    
    // Analyze emotion and generate response
    analyzeEmotion(message);
    generateAIResponse(message);
}

function addMessageToChat(message, sender) {
    const chatMessages = document.getElementById('chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-bubble opacity-0';
    
    const timestamp = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
    
    if (sender === 'user') {
        messageDiv.className += ' bg-gray-50 p-4 rounded-2xl ml-12';
        messageDiv.innerHTML = `
            <div class="flex items-start space-x-3 justify-end">
                <div>
                    <p class="text-gray-800">${message}</p>
                    <p class="text-xs text-gray-500 mt-2">${timestamp}</p>
                </div>
                <div class="w-8 h-8 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center flex-shrink-0">
                    <span class="text-white text-sm">👤</span>
                </div>
            </div>
        `;
    } else {
        messageDiv.className += ' bg-gradient-to-r from-blue-50 to-teal-50 p-4 rounded-2xl mr-12';
        messageDiv.innerHTML = `
            <div class="flex items-start space-x-3">
                <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-teal-500 rounded-full flex items-center justify-center flex-shrink-0">
                    <span class="text-white text-sm">🤖</span>
                </div>
                <div>
                    <p class="text-gray-800">${message}</p>
                    <p class="text-xs text-gray-500 mt-2">${timestamp}</p>
                </div>
            </div>
        `;
    }
    
    chatMessages.appendChild(messageDiv);
    
    // Animate message appearance
    anime({
        targets: messageDiv,
        opacity: [0, 1],
        translateY: [20, 0],
        duration: 500,
        easing: 'easeOutExpo'
    });
    
    // Scroll to bottom
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    // Save to chat history
    chatHistory.push({
        sender: sender,
        message: message,
        timestamp: timestamp
    });
    saveChatHistory();
}

function analyzeEmotion(message) {
    // Simple emotion analysis based on keywords
    const positiveWords = ['好', '开心', '快乐', '棒', '喜欢', '感谢', '幸福', '满足', '兴奋', '愉快'];
    const negativeWords = ['难过', '伤心', '痛苦', '焦虑', '担心', '害怕', '孤独', '无助', '沮丧', '失望'];
    const neutralWords = ['一般', '还行', '可以', '还好', '普通', '平常'];
    
    let positiveScore = 0;
    let negativeScore = 0;
    
    positiveWords.forEach(word => {
        if (message.includes(word)) positiveScore++;
    });
    
    negativeWords.forEach(word => {
        if (message.includes(word)) negativeScore++;
    });
    
    let emotion = 'neutral';
    let emotionEmoji = '😐';
    let emotionText = '中性';
    
    if (positiveScore > negativeScore) {
        emotion = 'positive';
        emotionEmoji = '😊';
        emotionText = '积极';
    } else if (negativeScore > positiveScore) {
        emotion = 'negative';
        emotionEmoji = '😔';
        emotionText = '消极';
    }
    
    // Update emotion display
    document.getElementById('current-emotion-emoji').textContent = emotionEmoji;
    document.getElementById('current-emotion-text').textContent = emotionText;
    
    // Update confidence level (mock data)
    const confidence = Math.floor(Math.random() * 20) + 75;
    document.getElementById('confidence-level').textContent = confidence + '%';
    
    currentEmotion = emotion;
    
    // Check for crisis keywords
    checkForCrisis(message);
}

function generateAIResponse(userMessage) {
    // Show typing indicator
    showTypingIndicator();
    
    setTimeout(() => {
        hideTypingIndicator();
        
        const response = getAIResponse(userMessage);
        addMessageToChat(response, 'ai');
        updateTherapySuggestions(userMessage);
    }, 1500 + Math.random() * 1000);
}

function getAIResponse(message) {
    // Simple response generation based on keywords and emotion
    const responses = {
        positive: [
            '听到您感觉良好我也很高兴！继续保持这种积极的心态对您的心理健康很有益处。',
            '您的积极情绪很有感染力。能和我分享一下是什么让您感到开心吗？',
            '保持这样的心态真的很棒！有什么具体的事情或经历让您感到满足吗？'
        ],
        negative: [
            '我理解您现在的感受。每个人都会经历困难时期，这完全是正常的。让我们一起探讨一下您的情况吧。',
            '听起来您正在经历一些挑战。请记住，寻求帮助是勇敢的表现。我在这里支持您。',
            '我感受到您的困扰。让我们一起找出让您感到更好的方法。您愿意分享更多细节吗？'
        ],
        neutral: [
            '谢谢您与我分享。能告诉我更多关于您现在的感受吗？',
            '我理解了。有什么特别的事情想要讨论或探索的吗？',
            '好的。让我们一起看看如何让您的一天变得更加美好。'
        ]
    };
    
    // Check for specific topics
    if (message.includes('焦虑') || message.includes('担心')) {
        return '我注意到您提到了焦虑的感受。焦虑是很常见的情绪，我们可以尝试一些呼吸练习或正念技巧来帮助您缓解。您想要我指导您进行一个简单的放松练习吗？';
    }
    
    if (message.includes('抑郁') || message.includes('沮丧')) {
        return '抑郁的感觉确实很沉重。请记住，您并不孤单，我在这里陪伴您。有时候，将感受表达出来本身就是一种治疗。您愿意和我多聊聊您的感受吗？';
    }
    
    if (message.includes('压力') || message.includes('紧张')) {
        return '压力是现代生活中常见的挑战。识别压力源是管理压力的第一步。能和我分享一下让您感到压力的具体情况吗？这样我们可以一起找到应对策略。';
    }
    
    if (message.includes('睡眠')) {
        return '睡眠对心理健康非常重要。睡眠质量不好会影响我们的情绪和认知功能。您最近的睡眠模式是什么样的？我们可以讨论一些改善睡眠的方法。';
    }
    
    // Return random response based on emotion
    const emotionResponses = responses[currentEmotion] || responses.neutral;
    return emotionResponses[Math.floor(Math.random() * emotionResponses.length)];
}

function showTypingIndicator() {
    isTyping = true;
    const chatMessages = document.getElementById('chat-messages');
    const typingDiv = document.createElement('div');
    typingDiv.id = 'typing-indicator';
    typingDiv.className = 'message-bubble bg-gradient-to-r from-blue-50 to-teal-50 p-4 rounded-2xl mr-12 opacity-0';
    typingDiv.innerHTML = `
        <div class="flex items-start space-x-3">
            <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-teal-500 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-white text-sm">🤖</span>
            </div>
            <div class="flex space-x-1">
                <div class="w-2 h-2 bg-gray-400 rounded-full typing-indicator"></div>
                <div class="w-2 h-2 bg-gray-400 rounded-full typing-indicator" style="animation-delay: 0.2s;"></div>
                <div class="w-2 h-2 bg-gray-400 rounded-full typing-indicator" style="animation-delay: 0.4s;"></div>
            </div>
        </div>
    `;
    
    chatMessages.appendChild(typingDiv);
    
    anime({
        targets: typingDiv,
        opacity: [0, 1],
        duration: 300,
        easing: 'easeOutExpo'
    });
    
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function hideTypingIndicator() {
    isTyping = false;
    const typingIndicator = document.getElementById('typing-indicator');
    if (typingIndicator) {
        anime({
            targets: typingIndicator,
            opacity: [1, 0],
            duration: 300,
            easing: 'easeOutExpo',
            complete: function() {
                typingIndicator.remove();
            }
        });
    }
}

function checkForCrisis(message) {
    const crisisKeywords = ['自杀', '自残', '结束生命', '不想活', '死了算了', '结束一切', '伤害自己'];
    const hasCrisisKeyword = crisisKeywords.some(keyword => message.includes(keyword));
    
    if (hasCrisisKeyword) {
        setTimeout(() => {
            showCrisisAlert();
        }, 2000);
    }
}

function showCrisisAlert() {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-50 border-l-4 border-red-400 p-4 rounded-lg shadow-lg z-50 max-w-sm';
    alertDiv.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                </svg>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-red-800">重要提醒</h3>
                <p class="mt-1 text-sm text-red-700">我们检测到您可能处于危机状态。请立即联系专业帮助：</p>
                <p class="mt-2 text-sm font-medium text-red-800">心理危机热线: 400-161-9995</p>
                <div class="mt-3">
                    <button onclick="window.location.href='crisis.html'" class="text-sm text-red-600 hover:text-red-500 font-medium">
                        查看紧急支持资源 →
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(alertDiv);
    
    // Auto remove after 10 seconds
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 10000);
}

function updateTherapySuggestions(userMessage) {
    const suggestions = [
        {
            title: '正念呼吸',
            description: '专注于呼吸，缓解当下焦虑',
            color: 'blue'
        },
        {
            title: '身体扫描',
            description: '觉察身体感受，释放紧张',
            color: 'green'
        },
        {
            title: '感恩练习',
            description: '记录今天值得感恩的事情',
            color: 'purple'
        },
        {
            title: '情绪日记',
            description: '记录和分析情绪变化',
            color: 'indigo'
        }
    ];
    
    const suggestionsContainer = document.getElementById('therapy-suggestions');
    suggestionsContainer.innerHTML = '';
    
    // Randomly select 3 suggestions
    const selectedSuggestions = suggestions.sort(() => 0.5 - Math.random()).slice(0, 3);
    
    selectedSuggestions.forEach(suggestion => {
        const suggestionDiv = document.createElement('div');
        suggestionDiv.className = `p-3 bg-${suggestion.color}-50 rounded-lg cursor-pointer hover:bg-${suggestion.color}-100 transition-colors`;
        suggestionDiv.innerHTML = `
            <h4 class="text-sm font-medium text-${suggestion.color}-800 mb-1">${suggestion.title}</h4>
            <p class="text-xs text-${suggestion.color}-600">${suggestion.description}</p>
        `;
        
        suggestionDiv.addEventListener('click', () => {
            showExerciseModal(suggestion.title, suggestion.description);
        });
        
        suggestionsContainer.appendChild(suggestionDiv);
    });
}

function showExerciseModal(title, description) {
    // Create modal for therapy exercises
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl p-8 max-w-md w-full">
            <h3 class="text-xl font-semibold text-gray-800 mb-4">${title}</h3>
            <p class="text-gray-600 mb-6">${description}</p>
            <div class="bg-blue-50 p-4 rounded-lg mb-6">
                <p class="text-sm text-blue-800">练习指导将在这里显示...</p>
            </div>
            <div class="flex space-x-3">
                <button onclick="this.closest('.fixed').remove()" class="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition-colors">
                    稍后练习
                </button>
                <button onclick="startExercise('${title}')" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors">
                    开始练习
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Animate modal appearance
    anime({
        targets: modal.querySelector('div'),
        scale: [0.9, 1],
        opacity: [0, 1],
        duration: 300,
        easing: 'easeOutExpo'
    });
}

// Quick action functions
function quickMoodCheck() {
    const moods = ['😊 很好', '🙂 不错', '😐 一般', '😔 不太好', '😢 很差'];
    
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl p-8 max-w-md w-full">
            <h3 class="text-xl font-semibold text-gray-800 mb-6 text-center">今天感觉如何？</h3>
            <div class="grid grid-cols-2 gap-3 mb-6">
                ${moods.map(mood => `
                    <button onclick="selectMood('${mood}')" class="mood-btn p-4 rounded-lg border-2 border-gray-200 hover:border-blue-500 transition-colors text-center">
                        <div class="text-2xl mb-2">${mood.split(' ')[0]}</div>
                        <div class="text-sm text-gray-700">${mood.split(' ')[1]}</div>
                    </button>
                `).join('')}
            </div>
            <button onclick="this.closest('.fixed').remove()" class="w-full bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition-colors">
                取消
            </button>
        </div>
    `;
    
    document.body.appendChild(modal);
}

function selectMood(mood) {
    // Save mood and close modal
    const moodData = {
        mood: mood,
        timestamp: new Date().toISOString()
    };
    
    let moodHistory = JSON.parse(localStorage.getItem('moodHistory') || '[]');
    moodHistory.push(moodData);
    localStorage.setItem('moodHistory', JSON.stringify(moodHistory));
    
    // Close modal
    document.querySelector('.fixed').remove();
    
    // Show confirmation
    const confirmation = document.createElement('div');
    confirmation.className = 'fixed top-4 right-4 bg-green-50 border-l-4 border-green-400 p-4 rounded-lg shadow-lg z-50';
    confirmation.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                </svg>
            </div>
            <div class="ml-3">
                <p class="text-sm font-medium text-green-800">情绪记录已保存</p>
                <p class="text-sm text-green-700">感谢您分享感受</p>
            </div>
        </div>
    `;
    
    document.body.appendChild(confirmation);
    
    setTimeout(() => {
        if (confirmation.parentNode) {
            confirmation.remove();
        }
    }, 3000);
}

function breathingExercise() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl p-8 max-w-md w-full text-center">
            <h3 class="text-xl font-semibold text-gray-800 mb-6">4-7-8 呼吸法</h3>
            <div class="mb-6">
                <div id="breathing-circle" class="w-32 h-32 bg-gradient-to-br from-blue-400 to-teal-400 rounded-full mx-auto flex items-center justify-center text-white font-bold text-lg">
                    准备开始
                </div>
            </div>
            <p class="text-gray-600 mb-6">吸气4秒 → 屏息7秒 → 呼气8秒</p>
            <div class="flex space-x-3">
                <button onclick="this.closest('.fixed').remove()" class="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition-colors">
                    退出
                </button>
                <button onclick="startBreathing()" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors">
                    开始练习
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
}

function startBreathing() {
    const circle = document.getElementById('breathing-circle');
    let phase = 0; // 0: inhale, 1: hold, 2: exhale
    let count = 0;
    
    function breathingCycle() {
        if (phase === 0) {
            // Inhale
            circle.textContent = `吸气 ${count + 1}`;
            anime({
                targets: circle,
                scale: [1, 1.3],
                duration: 4000,
                easing: 'easeInOutSine'
            });
            count++;
            if (count >= 4) {
                phase = 1;
                count = 0;
            }
        } else if (phase === 1) {
            // Hold
            circle.textContent = `屏息 ${count + 1}`;
            count++;
            if (count >= 7) {
                phase = 2;
                count = 0;
            }
        } else {
            // Exhale
            circle.textContent = `呼气 ${count + 1}`;
            anime({
                targets: circle,
                scale: [1.3, 1],
                duration: 8000,
                easing: 'easeInOutSine'
            });
            count++;
            if (count >= 8) {
                phase = 0;
                count = 0;
            }
        }
    }
    
    const interval = setInterval(breathingCycle, 1000);
    
    // Stop after 2 minutes
    setTimeout(() => {
        clearInterval(interval);
        circle.textContent = '练习完成';
    }, 120000);
}

function crisisSupport() {
    window.location.href = 'crisis.html';
}

function startExercise(exerciseType) {
    // Close modal and start exercise
    document.querySelector('.fixed').remove();
    
    // Show exercise in progress
    const notification = document.createElement('div');
    notification.className = 'fixed top-4 right-4 bg-blue-50 border-l-4 border-blue-400 p-4 rounded-lg shadow-lg z-50';
    notification.innerHTML = `
        <div class="flex">
            <div class="flex-shrink-0">
                <svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                </svg>
            </div>
            <div class="ml-3">
                <p class="text-sm font-medium text-blue-800">开始${exerciseType}练习</p>
                <p class="text-sm text-blue-700">请按照指导进行练习</p>
            </div>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

// Local storage functions
function saveChatHistory() {
    localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
}

function loadChatHistory() {
    const saved = localStorage.getItem('chatHistory');
    if (saved) {
        chatHistory = JSON.parse(saved);
        // Optionally display last few messages
    }
}

// Utility functions
function simulateTypingIndicator() {
    // This function can be used to show when AI is "thinking"
    // Implementation depends on specific requirements
}

// Export functions for global access
window.startChat = startChat;
window.sendMessage = sendMessage;
window.quickMoodCheck = quickMoodCheck;
window.breathingExercise = breathingExercise;
window.crisisSupport = crisisSupport;